package com.mini.demos.webgame.codec;

import java.nio.charset.CharacterCodingException;
import java.util.logging.Logger;

import org.apache.mina.core.buffer.IoBuffer;

import com.mini.demos.webgame.msg.AbstractGameMsg;
import com.mini.demos.webgame.msg.LoginMsg;
import com.mini.demos.webgame.msg.MsgHead;
import com.mini.demos.webgame.util.CommandConstants;
import com.mini.demos.webgame.util.Constants;

public class LoginDecoder extends AbstractDecoder {
	
	private Logger log = Logger.getLogger("loginDecoder");

	@Override
	public AbstractGameMsg decodeBody(IoBuffer buffer, MsgHead head) {
		String loginBody = "";
		try{
			loginBody = buffer.getString(Constants.charset.newDecoder());
		}catch(CharacterCodingException cce){
			int bodyLength = head.getTotalLength()-Constants.HEAD_LEN;
			byte[] bodys = new byte[bodyLength];
			buffer.get(bodys);
			loginBody = new String(bodys);
		}
		log.info("loginBody:"+loginBody);
		LoginMsg loginMsg = new LoginMsg();
		String[] loginMsgBody = loginBody.split(CommandConstants.COMMAND_SPLIT);
		loginMsg.setHead(head);
		loginMsg.setName(loginMsgBody[0]);
		loginMsg.setPwd(loginMsgBody[1]);
		System.out.println("name:" +loginMsg.getName() + " pwd:" + loginMsg.getPwd());
		return loginMsg;
	}

	@Override
	public boolean isLegalCommand(int commandId) {
		if(commandId == CommandConstants.LOGIN){
			return true;
		}
		return false;
	}

}
